﻿@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Index_Layout.cshtml";
    ViewFWUser currentUserInfo = base.Context.Session.GetUserInfo();
}
@if (!currentUserInfo.IsHaveRights("Demo_School_Test", "00"))
{
    throw new Exception("您没有该页面的权限");
}

@section styles{
}
@section scripts{
   @*<script src="~/js/views/Main/Home/index.js" asp-append-version="true"></script>*@
}

<div data-toggle="topjui-layout" data-options="fit:true">
    <div data-options="region:'center',title:'',fit:false,split:true,border:false">
        <table id="myDg"></table>

        <div id="myDg-toolbar" class="topjui-toolbar" data-options="
        grid:{
            type:'treegrid',
            id:'myDg',
            parentIdField:'pid'
            }">
            @if (currentUserInfo.IsHaveRights("Demo_School_Test", "01"))
            {
                <a href="javascript:void(0)"
                       data-toggle="topjui-menubutton"
                       data-options="
                       menu:'#addSubMenu',
                       hasDownArrow:true,
                       iconCls:'fa fa-plus'
                    ">@L("新增")
                </a>

                <div id="addSubMenu" class="topjui-toolbar" style="width:120px;" data-options="hideOnUnhover:false">
                    <div data-toggle="topjui-menubutton"
                            data-options="iconCls:'fa fa-plus',onClick: function(){oepnAddDiag(true)}">
                        @L("新增根节点")
                    </div>
                    <div data-toggle="topjui-menubutton"
                            data-options="iconCls:'fa fa-plus',onClick: oepnAddDiag">
                        @L("新增子节点")
                    </div>
                </div>
            }

            @if (currentUserInfo.IsHaveRights("Demo_School_Test", "02"))
            {
                @*<a id="add" href="javascript:void(0)" data-toggle="topjui-menubutton"
                    data-options="iconCls:'fa fa-pencil',btnCls:'topjui-btn-blue',onClick: openEditDiag">
                    @L("编辑")
                </a>*@
            }
            
            @if (currentUserInfo.IsHaveRights("Demo_School_Test", "03"))
            {
                <a href="javascript:void(0)" data-toggle="topjui-menubutton" data-options="
                    method:'doAjax',
                    btnCls:'topjui-btn-delete',
                    extend: '#myDg-toolbar',
                    iconCls:'fa fa-trash',
                    confirmMsg:'@L("确实删除选中的数据吗?")',
                    grid: {uncheckedMsg:'@L("请先勾选要删除的数据")',param:'id:id'},
                    url:'/api/services/app/DemoSchoolTest/BatchDelete' ">@L("删除")
               </a>
            }

            <a href="javascript:void(0)"
                data-toggle="topjui-menubutton"
                data-options="
                method:'filter',
                extend: '#myDg-toolbar',
                btnCls:'topjui-btn-filter'">@L("过滤")
           </a>

            <a href="javascript:void(0)"
                data-toggle="topjui-menubutton"
                data-options="
                method:'expandAll',
                extend: '#myDg-toolbar',
                iconCls:'fa fa-angle-down',
                btnCls:'topjui-btn-blue'">@L("展开全部")
           </a>

            <a href="javascript:void(0)"
                data-toggle="topjui-menubutton"
                data-options="method:
                'collapseAll',
                extend: '#myDg-toolbar',
                iconCls:'fa fa-angle-up',
                btnCls:'topjui-btn-blue'">@L("折叠全部")
            </a>


            @*<a href="javascript:void(0)"
                data-toggle="topjui-menubutton"
                data-options="
                    btnCls:'topjui-btn-black',
                    onClick:myQuery">@L("自定义方法")
              </a>*@
        </div>
    </div>
</div>

<!--自定义修改,尽量不要改框架的代码,修改全放这里,如果要修改框架代码,尽量在这里写个方法,在框架调用-->
<script>
var demoSchoolTestEdit={
    queryObj: $.dm.getQueryObj(), // URL的参数
    buInfo: $.dm.getBuInfo(), // 门店信息
    userInfo: $.dm.getUserInfo() // 用户信息
}
</script>

<!--全局变量和公共方法-->
<script>
    // 处理添加和编辑的时候load之后调用的方法
    function addOrEditLoad(type,uuid) {
        if (type == "add") {
        }

        if (type == "edit") {
        }
    }

    // 保存时用户的自定义验证
    function userValidate() {
        //var myFormProductGUIDValue = $("#myFormProductGUID").iCombobox("getValue");
        //if (myFormProductGUIDValue.length != 36) {
        //    layer.msg("@L("请选择对应的产品")");
        //    return false;
        //}

        return true;
    }
</script>

<!--表格操作-->
<script>
    // 定义初始化过滤条件
    var myDgInitFilter = null;
    //if (queryObj.classGUID) {
    //    myDgInitFilter = {
    //    Type: "and",
    //    conditions: [{
    //        Attribute: "classGUID",
    //        Datatype: "uniqueidentifier",
    //        Operatoer: "eq",
    //        Value: queryObj.classGUID
    //    }]
    //   };
    //}

    // 获取过滤条件
    function getFilters() {
        var initFilter = null;
        var filter = $.ei.getFilters(); // 获取界面查询条件

        // 如果有初始化条件那么把初始化的条件加上去
        if (myDgInitFilter && myDgInitFilter.conditions) {
            initFilter = myDgInitFilter;
            if (filter) {
                initFilter.conditions = _.union(filter.conditions, myDgInitFilter.conditions);
            }
        } else if (filter) {
            initFilter = filter; // 没有初始化条件 那么用查询的条件
        }

        if (initFilter) {
            return JSON.stringify(initFilter);
        } else {
            return null;
        }
    }

    // 表格查询
    function searchQuery() {
        var param = $('#myDg').iTreegrid('options').queryParams;
        param.filter = getFilters();
        $('#myDg').iTreegrid('load', param);
    }

    $(function () {
         var dg = $('#myDg').iTreegrid({
            url: '/api/services/app/DemoSchoolTest/GetTreeGird',
            fitColumns: true,
            expandUrl: '/api/services/app/DemoSchoolTest/GetTreeGird?pid={id}',
            queryParams:{
                order: 'fullCode  asc',
                pageIndex: 1,
                pageSize: 999,
                filter: getFilters()
            },
            columns: [
                [
                    {
                        field: 'id',
                        title: 'id',
                        checkbox: true,
                    },
                    { field: 'text', title: '@L("名称")', width: 120 },
                    { field: 'code', title: '@L("层级编码")', width: 120 },
                    {
                        formatter: operateFormatter,
                        field: 'createTime',
                        title: '@L("操作")',
                        sortable: true,
                        width: 100
                    }
                ]
            ],
            onDblClickRow: function (a) {
                @if (currentUserInfo.IsHaveRights("Demo_School_Test", "02")){
                <text>
                openEditDiag(a.id);
                </text>}
                else{
                <text>
                openDetailDiag(a.id);
                </text>}
            },
            loadFilter: function (data) {  // 用于客户端过滤数据
                //var filterData = _.filter(data, function (item, index, lst) {
                //    if (item.code.indexOf("001")!=-1) {
                //        return true;
                //    }
                //});
                //return filterData;
                return data;
            }
        });
    })
   

    function operateFormatter(value, row, index) {
        if (row.pid) {
            var htmlStr = '<button class="layui-btn layui-btn-xs" onclick="moveUp(\'{0}\')">上移</button>'.format(row.id);
            htmlStr += '<button class="layui-btn layui-btn-xs layui-btn-warm" onclick="moveDown(\'{0}\')">下移</button>'.format(row.id);
            return htmlStr;
        }
    }

     function moveUp(id) {
        var selectRow = $("tr[node-id='{0}']".format(id));
        var pre = selectRow.prev();// 此处获得上一节点，关键
        if (typeof (pre.attr("node-id")) == "undefined" || pre.attr("node-id").indexOf("L") == 0) {
            $.messager.alert('提示', '无法移动');
        } else {
            var preid = pre.attr("node-id");
            var firstItem = $("#myDg").treegrid("find", id);
            var secondItem = $("#myDg").treegrid("find", preid);
            var preCode = firstItem.code;
            var afterCode = secondItem.code;

            firstItem.code = afterCode;

            $.iMessager.progress({ 'text': '@L("处理中……")' });
            abp.ajax({
                url: '/api/services/app/DemoSchoolTest/UpdateByDto',
                data: { id: id, fullCode: afterCode}
            }).done(function () {
                abp.ajax({
                    url: '/api/services/app/DemoSchoolTest/UpdateByDto',
                    data: { id: preid, fullCode: preCode }
                }).done(function () {
                    $("#myDg").treegrid("pop", id);
                    $('#myDg').iTreegrid('update', {
                        id: preid,
                        row: {
                            code: preCode
                        }
                    });

                    $("#myDg").treegrid("insert", { before: preid, data: firstItem });
                    $("#myDg").treegrid("select", id);
                });
            });
        }
    }

    function moveDown(id) {
        var selectRow = $("tr[node-id='{0}']".format(id));
        var next = selectRow.next(); // 此处获得下一节点，关键
        if (typeof (next.attr("node-id")) == "undefined" || next.attr("node-id").indexOf("L") == 0) {
            $.messager.alert('提示','无法移动');
        } else {
            var nextId = next.attr("node-id");
            var firstItem = $("#myDg").treegrid("find", id);
            var secondItem = $("#myDg").treegrid("find", nextId);

            var preCode = firstItem.code;
            var afterCode = secondItem.code;

            firstItem.code = afterCode;
            secondItem.code = preCode;

            $.iMessager.progress({ 'text': '@L("处理中……")' });
            abp.ajax({
                url: '/api/services/app/DemoSchoolTest/UpdateByDto',
                data: { id: id, fullCode: afterCode }
            }).done(function () {
                abp.ajax({
                    url: '/api/services/app/DemoSchoolTest/UpdateByDto',
                    data: { id: nextId, fullCode: preCode }
                }).done(function () {
                    $('#myDg').iTreegrid('update', {
                        id: id,
                        row: {
                            code: afterCode,
                        }
                    });

                    $("#myDg").treegrid("pop", nextId);
                    $("#myDg").treegrid("insert", { before: id, data: secondItem })
                    $("#myDg").treegrid("select", id);
                });
            });
        }
    }
</script>

<!--按钮相关-->
<script>
    function oepnAddDiag(isRoot) {
        $("#addSubMenu").iMenu('hide');
        var selected = $('#myDg').iTreegrid('getSelected');
        var result={};
        if (!isRoot) {
            if (selected) {
               result = {
                    parentGUID: selected.id
                };

            } else {
                layer.msg("@L("请选择一行作为子节点的父节点!")");
                return;
            }
        }
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("新增学院表(树)")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            href: '/Demo/DemoSchoolTest/DemoSchoolTestEdit?mode=1',
            buttons: [{
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    saveDate("saveAndClose");
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
                $editDialog.form('load', result);
                if (isRoot) {
                    $("#divMyFormParentGUID").hide();
                }

                addOrEditLoad("add");
            }
        });
    }

    function openEditDiag(uuid) {
         if (!uuid) {
            var selectedRow = $('#myDg').iDatagrid('getSelected');
            uuid = selectedRow.id;
        }
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("编辑学院表(树)")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            href: '/Demo/DemoSchoolTest/DemoSchoolTestEdit?uuid=' + uuid+'&mode=2',
            buttons: [
            @if (currentUserInfo.IsHaveRights("Demo_School_Test", "02")) {
            <text>
            {
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    saveDate("saveAndClose");
                }
            },
            </text>}
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
                addOrEditLoad("edit",uuid);
                var data = { 'id': uuid };
                var options = {
                    url: '/api/services/app/DemoSchoolTest/GetViewDto',
                    maskJqSelect: '#myFormDialog',
                    data:data
                };

                var success = function (result) {
                    $editDialog.form('load', result);

                    // 绑定combox
                    $editDialog.find('[data-toggle="topjui-combobox"]').each(function (b) {
                        var c = $(this);
                        var opt = getOptionsJson(c);
                        if (opt.queryParams.viewName) {
                            c.iCombobox(opt);
                        }
                    });

                    // 在这里进行绑定UeEditor
                    $editDialog.find('[data-toggle="topjui-ueditor"]').each(function (b) {
                        var c = $(this);
                        var name = c.attr('name');
                        var opt = getOptionsJson(c);
                        var id = opt.id;
                        var ue = UE.getEditor(id);
                        ue.ready(function () {
                            ue.setContent(result[name]);
                        });
                    });

                    @if (!currentUserInfo.IsHaveRights("Demo_School_Test", "02")) {
                    <text>
                    $editDialog.form('readonly');
                    </text>}
                }

                abp.ajax(options).done(success);
            }
        });
    }

    // operate表示操作类型有 save saveAndClose saveAndNew
    function saveDate(operate) {
        // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
        $.iMessager.progress({ 'text': '@L("保存中……")' });
        var isValid = $('#myFormDialog').iForm('validate'); //  提交数据表单数据时进行表单验证
        var isUserValid = userValidate();
        if (!isValid || !isUserValid) {
            layer.msg("@L("格式不正确,请填写对应的必填项!")");
            $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
            return;
        }

        var data = $.dm.parseQueryString($('#myFormDialog').serialize());
        var options = {
            url: '/api/services/app/DemoSchoolTest/CreateByDto',
            data: data
        };

        // 有ID就是更新
        if (data.id) {
            options.url = '/api/services/app/DemoSchoolTest/UpdateByDto'
        }
        var success = function (result) {
            $.iMessager.show({ title: '@L("我的消息")', msg: '@L("保存成功")', timeout: 2000, showType: 'slide' });// '消息窗口'组件
            $('#myFormDialog').iDialog('close');// 销毁dialog面板
            refreshTreeGrid();
        }
        abp.ajax(options).done(success);
    }

    function openDetailDiag(uuid) {
        if (!uuid) {
            var selectedRow = $('#myDg').iDatagrid('getSelected');
            uuid = selectedRow.id;
        }
        var $editDialog = $('<form id="myDetailDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("查看")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            href: '/Demo/DemoSchoolTest/DemoSchoolTestDetail?uuid=' + uuid,
            buttons: [{
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myDetailDialog').dialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
                var data = { 'id': uuid };
                var options = {
                    url: '/api/services/app/DemoSchoolTest/GetViewDto',
                    maskJqSelect: '#myDetailDialog',
                    data:data
                };

                var success = function (result) {
                    $("#DemoSchoolTestDetailTableTemplate").tmpl(result)
                        .appendTo("#DemoSchoolTestDetailTable");
                }
                abp.ajax(options).done(success);
            }
        });
    }

    // 删除行数据
    function deleteRow(id) {
        $.messager.confirm("@L("提示")", "@L("确定要删除该条数据吗?")", function (result) {
            if (result) {
                $.iMessager.progress({ 'text': '@L("处理中……")' });
                var data={'id':id};
                var options = {
                    url: '/api/services/app/DemoSchoolTest/DeleteByDto',
                    maskJqSelect: '#myDg'
                };

                var success = function (result) {
                    $("#myDg").iTreegrid("remove", id);
                    $.iMessager.show({ title: '@L("我的消息")', msg: '@L("删除成功")', timeout: 2000, showType: 'slide' });// '消息窗口'组件
                }

                abp.ajax(options).done(success);
            }
        })
    }

    // 自定义方法
    function myQuery() {
        alert("123");
        // 选择一行
        $('#myDg').datagrid('selectRow', 1);
        // 提示信息
        //$.iMessager.alert('自定义方法', '自定义方法被执行了！', 'messager-info');

        //var checkedRows = $('#productDg').iDatagrid('getChecked');
        //console.log(checkedRows);

        //var options = $('#myDg').iDatagrid('options');
        //var selectedRow = $('#myDg').iDatagrid('getSelected');
        //console.log(selectedRow);

        // 提交参数查询表格数据
        //$('#productDg').iDatagrid('reload', {
        //    name: $('#name').iTextbox('getValue'),
        //    code: $('#code').iTextbox('getValue')
        //});
    }
</script>
